package com.zw.yzk.kabu.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.HomePageCosAdapter;
import com.zw.yzk.kabu.base.BaseActivity;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.utils.LogUtils;
import com.zw.yzk.kabu.internal.component.DaggerHomePageComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.HomePageModule;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.management.ToolbarBuilder;
import com.zw.yzk.kabu.model.CosplayModel;
import com.zw.yzk.kabu.model.HomepageHeaderModel;
import com.zw.yzk.kabu.presenter.HomePagePresenter;
import com.zw.yzk.kabu.utils.CircleTransform;
import com.zw.yzk.kabu.utils.PhoneUtils;
import com.zw.yzk.kabu.view.activity.imagedetails.ImageDetailsActivity;
import com.zw.yzk.kabu.view.view.HomepageView;
import com.zw.yzk.refresh.library.PullToRefreshLayout;
import com.zw.yzk.refresh.library.RefreshBuilder;
import com.zw.yzk.refresh.library.State;
import com.zw.yzk.refresh.library.loadmore.DefaultLoadMoreViewCreator;

import javax.inject.Inject;

import java.util.List;

/**
 * Created by zhanwei on 2017/1/11.
 */

public class HomePageActivity extends BaseActivity implements HomepageView, HomePageCosAdapter.CosActionListener {

    @Bind(R.id.refresh_view)
    PullToRefreshLayout refreshLayout;
    @Bind(R.id.publish_list)
    RecyclerView publishList;
    @Bind(R.id.empty)
    TextView empty;
    @Bind(R.id.right_image)
    ImageView skin;
    @Bind(R.id.tool_bar_title)
    TextView title;

    //头部信息
    private View header;
    private ImageView background;
    private TextView nickName;
    private TextView remark;
    private ImageView head;
    private ImageView takePhoto;
    private TextView applyFamous;
    private TextView concernCount;
    private TextView fansCount;
    private TextView albumCount;
    private ImageView selectTopImage;


    @Inject
    HomePagePresenter presenter;
    private HomePageCosAdapter cosAdapter;
    private int ownerId;
    private String ownerName;
    private boolean self;
    private String headImgUrl;

    public static void startHomePageActivity(Context context, int ownerId, String nickName) {
        Intent intent = new Intent(context, HomePageActivity.class);
        intent.putExtra(ActivityConstant.HOME_PAGE_ID, ownerId);
        if(!TextUtils.isEmpty(nickName)) {
            intent.putExtra(ActivityConstant.HOME_PAGE_NICK_NAME, nickName);
        }
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_home_page;
    }

    @Override
    public void iniToolbar(BaseActivity activity) {
        ToolbarBuilder
                .createBuilder(this)
                .setTitle(getResources().getString(R.string.own_home_page))
                .build();
    }

    @Override
    public void initComponent() {
        DaggerHomePageComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .homePageModule(new HomePageModule())
                .build()
                .inject(this);
        presenter.setHomepageView(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ownerId = getIntent().getIntExtra(ActivityConstant.HOME_PAGE_ID, 0);
        ownerName = getIntent().getStringExtra(ActivityConstant.HOME_PAGE_NICK_NAME);

        User user = DataBaseManager.getInstance().getLoginUser();
        self = (user != null && user.getUserId() == ownerId)
                || (user != null && user.getNickName().equals(ownerName));
        if (self) {
            skin.setImageResource(R.drawable.ic_skin);
        } else {
            skin.setImageResource(R.drawable.selector_home_page_concern);
        }
        skin.setVisibility(View.VISIBLE);

        getUploadImageToken();
        initRecyclerView();
        addRecyclerViewHeader();
        getHomePageInfo(ownerId, ownerName, 0, 0);

        LoadingDialogManager.getInstance().showLoadingDialog(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getCosplayListSuccess(List<CosplayModel> modelList) {
        if (refreshLayout.isLoading()) {
            cosAdapter.add(modelList);
            refreshLayout.loadMoreFinish(modelList.isEmpty() ? State.LOAD_ALL : State.LOADING_SUCCEED);
        } else {
            cosAdapter.refresh(modelList);
            refreshLayout.refreshFinish(State.REFRESH_SUCCEED);
        }
        //是否显示空提示
        refreshEmptyStatus(cosAdapter.getItemCount() == 0);
    }

    @Override
    public void getCosplayListFail() {
        refreshLayout.finishRefreshingOrLoadingStatus(false);
    }

    @Override
    public void setHeaderInfo(HomepageHeaderModel model) {
        ownerId = model.getUserId();
        ownerName = model.getNickName();

        if (!self) {
            title.setText(model.getNickName());
            skin.setSelected(model.getFollowState() == 1 || model.getFollowState() == 3);
        }
        nickName.setText(model.getNickName());
        remark.setText(model.getRemark());
        concernCount.setText(String.valueOf(model.getConcernCount()));
        fansCount.setText(String.valueOf(model.getFansCount()));
        albumCount.setText(String.valueOf(model.getAlbumCount()));

        if (model.isStar()) {
            if (model.getRank() <= 1000) {
                applyFamous.setBackgroundResource(R.drawable.ic_ranking_gold);
            } else if (model.getRank() <= 5000) {
                applyFamous.setBackgroundResource(R.drawable.ic_ranking_sliver);
            } else {
                applyFamous.setBackgroundResource(R.drawable.ic_ranking_bronze);
            }
            applyFamous.setText(String.valueOf(model.getRank()));
        } else {
            applyFamous.setVisibility(View.GONE);
        }
        applyFamous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(HomePageActivity.this, ApplyFamousActivity.class));
            }
        });
        header.findViewById(R.id.layout_fans).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomePageActivity.this, FansWallActivity.class);
                intent.putExtra(ActivityConstant.FANS_OWNER_ID, ownerId);
                startActivity(intent);
            }
        });
        header.findViewById(R.id.layout_concern).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomePageActivity.this, ConcernedWallActivity.class);
                intent.putExtra(ActivityConstant.CONCERNED_OWNER_ID, ownerId);
                startActivity(intent);
            }
        });
        header.findViewById(R.id.layout_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlbumActivity.startAlbumActivity(HomePageActivity.this, nickName.getText().toString(), ownerId);
            }
        });
        skin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (self) {
                    //进入自己的主页
                    startActivity(new Intent(HomePageActivity.this, SkinMallActivity.class));
                } else if (DataBaseManager.getInstance().getLoginUser() != null) {
                    //登录状态下进入别人的主页
                    skin.setSelected(!skin.isSelected());
                    if (skin.isSelected()) {
                        follow(true, ownerId);
                    } else {
                        follow(false, ownerId);
                    }
                } else {
                    //非登录状态下进入别人的主页
                    startActivity(new Intent(HomePageActivity.this, LoginActivity.class));
                }

            }
        });


        loadTopBg(model.getBackgroundUrl());
        headImgUrl = model.getHeadUrl();
        loadUserHead(model.getHeadUrl());
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage(true);
            }
        });
    }

    @Override
    public void refreshHeadSuccess() {
        final User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null || TextUtils.isEmpty(user.getHeadUrl())) {
            return;
        }
        loadUserHead(user.getHeadUrl());
        if (!TextUtils.isEmpty(user.getHomePage())) {
            loadTopBg(user.getHomePage());
        }

    }

    @Override
    public void praiseCos(CosplayModel model, boolean praise) {
        praise(model.getId(), praise);
    }

    @Override
    public void collectCos(CosplayModel model, boolean collect) {
        collect(model.getId(), collect);
    }

    @Override
    public void deleteCos(CosplayModel model) {
        delete(model.getId());
    }

    /**
     * 添加RecyclerViewHeader
     */
    private void addRecyclerViewHeader() {
        header = LayoutInflater.from(this).inflate(R.layout.recycler_header_own_home_page, null);
        background = (ImageView) header.findViewById(R.id.my_bg);
        nickName = (TextView) header.findViewById(R.id.nickName);
        remark = (TextView) header.findViewById(R.id.remark);
        head = (ImageView) header.findViewById(R.id.user_head);
        takePhoto = (ImageView) header.findViewById(R.id.take_photo);
        applyFamous = (TextView) header.findViewById(R.id.apply_famous);
        concernCount = (TextView) header.findViewById(R.id.concern_count);
        fansCount = (TextView) header.findViewById(R.id.fans_count);
        albumCount = (TextView) header.findViewById(R.id.album_count);
        selectTopImage = (ImageView) header.findViewById(R.id.select_top_image);

        nickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HomePageActivity.this, ModifyUserInfoActivity.class));
            }
        });


        head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(headImgUrl)) {
                    Rect rect = new Rect();
                    head.getGlobalVisibleRect(rect);
                    ImageDetailsActivity.startDetailsActivity(HomePageActivity.this, headImgUrl, rect);
                }
            }
        });

        selectTopImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage(false);
            }
        });

        refreshLayout.setHeader(header);
        checkUser();
    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        publishList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        cosAdapter = new HomePageCosAdapter(null, self);
        cosAdapter.setCosActionListener(this);
        publishList.setAdapter(cosAdapter);

        new RefreshBuilder.Builder(refreshLayout)
                .setLoadMoreViewCreator(new DefaultLoadMoreViewCreator())
                .setRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        getHomePageInfo(ownerId, ownerName, 0, 0);
                    }

                    @Override
                    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                        int count = cosAdapter.getItemCount();
                        getHomePageInfo(ownerId, ownerName, count, cosAdapter.getTotalList().get(count - 1).getId());
                    }
                }).build();
    }

    /**
     * 打开相机
     */
    private void selectImage(final boolean selectHead) {
        FunctionConfig functionConfig;
        if (selectHead) {
            functionConfig = new FunctionConfig.Builder()
                    .setEnableCamera(false)
                    .setEnableEdit(true)
                    .setEnableCrop(true)
                    .setEnableRotate(true)
                    .setCropSquare(true)
                    .setEnablePreview(true)
                    .setForceCrop(true)
                    .build();
        } else {
            functionConfig = new FunctionConfig.Builder()
                    .setEnableCamera(false)
                    .setEnableEdit(true)
                    .setEnableCrop(true)
                    .setEnableRotate(true)
                    .setCropSquare(false)
                    .setCropWidth(PhoneUtils.getScreenWidth(this))
                    .setCropHeight((int) (getResources().getDisplayMetrics().density * 200))
                    .setEnablePreview(true)
                    .setForceCrop(true)
                    .build();
        }

        GalleryFinal.openGallerySingle(ActivityConstant.OPEN_GALLERY, functionConfig, new GalleryFinal.OnHandlerResultCallback() {
            @Override
            public void onHandlerSuccess(int requestCode, List<PhotoInfo> resultList) {
                if (resultList.size() <= 0) {
                    ToastManager.getInstance().showToast(HomePageActivity.this, getResources().getString(R.string.read_file_error));
                    return;
                }
                //修改图片
                modifyUsrHead(resultList.get(0).getPhotoPath(), selectHead);
                //显示加载对话框
                LoadingDialogManager.getInstance().showLoadingDialog(HomePageActivity.this);
            }

            @Override
            public void onHandlerFailure(int requestCode, String errorMsg) {
                ToastManager.getInstance().showToast(HomePageActivity.this, errorMsg + "(" + requestCode + ")");
            }

        });
    }


    /**
     * 获取主页信息
     *
     * @param ownerId 主页id
     * @param start   开始索引
     */
    public void getHomePageInfo(int ownerId, String ownerName, int start, int lastId) {
        presenter.getHomePageInfo(ownerId, ownerName, start, lastId);
    }


    /**
     * 是否显示空提示
     *
     * @param show true:显示，false:不显示
     */
    private void refreshEmptyStatus(boolean show) {
//        empty.setVisibility(show ? View.VISIBLE : View.GONE);
        empty.setVisibility(View.GONE);
    }


    /**
     * 验证是否是进入当前用户的主页
     */
    private void checkUser() {
        if (!self) {
            takePhoto.setVisibility(View.GONE);
            nickName.setEnabled(false);
            applyFamous.setEnabled(false);
            nickName.setCompoundDrawables(null, null, null, null);
            selectTopImage.setVisibility(View.GONE);
        }
    }


    /**
     * 获取七牛图片上传token
     */
    private void getUploadImageToken() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null || !user.isLogin()) {
            return;
        }
        presenter.getUploadImageToken();
    }

    /**
     * 加载用户头像
     *
     * @param url 头像url
     */
    private void loadUserHead(String url) {
        Glide.with(this).load(url)
                .error(R.drawable.ic_default_head)
                .transform(new CircleTransform(this))
                .into(new SimpleTarget<GlideDrawable>() {
                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                        if (resource instanceof GlideBitmapDrawable) {
                            if (head != null) {
                                head.setImageBitmap(((GlideBitmapDrawable) resource).getBitmap());
                            }
                        }
                    }
                });
    }

    /**
     * 加载顶部背景
     *
     * @param url 背景
     */
    private void loadTopBg(final String url) {
        Glide.with(this)
                .load(url)
                .centerCrop()
                .error(R.drawable.im_default)
                .into(background);

        background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(url)) {
                    Rect rect = new Rect();
                    background.getGlobalVisibleRect(rect);
                    ImageDetailsActivity.startDetailsActivity(HomePageActivity.this, url, rect);
                }
            }
        });
    }

    /**
     * 修改个人头像
     *
     * @param filePath 文件路径
     * @param isHead   是否是头像 true:修改头像，false: 修改背景
     */
    private void modifyUsrHead(String filePath, boolean isHead) {
        presenter.modifyImage(filePath, isHead);
    }

    /**
     * 是否点赞
     *
     * @param cosplayId cosid
     * @param praise    true：点赞，false：取消
     */
    public void praise(int cosplayId, boolean praise) {
        presenter.praise(cosplayId, praise);
    }

    /**
     * 是否收藏
     *
     * @param cosplayId cosId
     * @param collect   true：收藏，false：取消
     */
    public void collect(int cosplayId, boolean collect) {
        presenter.collect(cosplayId, collect);
    }

    /**
     * 删除cos
     *
     * @param cosId cosId
     */
    public void delete(int cosId) {
        presenter.delete(cosId);
    }

    public void follow(boolean follow, int ownerId) {
        presenter.follow(ownerId, follow);
    }
}
